<?php

namespace App\Http\Middleware;

use App\Server\JwtServer;
use Closure;
use Illuminate\Http\Request;

class CheckApiLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //将token放入header中传输
        $token = $request->header('token');
        if (!$token) {
            return response()->json(['status' => 400, 'msg' => '无效token']);
        }
        $userId = JwtServer::decodeToken($token);
        if ($userId) {
            //将加密id解密传入下一步
            $request->attributes->add(['user_id' => $userId->user_id]);
        } else {
            return response()->json(['status' => 400, 'msg' => 'token过期']);
        }
        return $next($request);
    }
}